
/**
 * @fileoverview DateRangePicker control.
 * @link http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml
 * @link https://developers.google.com/closure/compiler/docs/js-for-compiler
 */



/**
 * Constructor of DateRangePicker.
 * @extends {controls.DatePicker} controls.DatePicker
 * @constructor
 */
controls.DateRangePicker = function() {
  controls.DatePicker.apply(this, arguments);

  /**
   * @type {string}
   * @const
   */
  var RANGE_SEPARATOR = ' - ';

  /** @inheritDoc */
  this.onClick = function(cell) {
    /** @type {!Date} */
    var date = new Date(Date.parse(cell.getAttribute('value')));
    /** @type {Node} */ var node = self_.getElement();

    if (first_) {
      node.setAttribute('data-start-date', +date);
      self_.getCalendar().clear();
      cell.className = 'active';
    } else {
      /** @type {number} */ var start = +node.getAttribute('data-start-date');
      /** @type {number} */ var end = +date;
      if (start > end) {
        end = start;
        start = +date;
      }
      node.setAttribute('data-start-date', start);
      node.setAttribute('data-end-date', end);

      self_.setValue(
          formatters.DateFormatter.format(new Date(start), self_.getFormat()) +
          RANGE_SEPARATOR +
          formatters.DateFormatter.format(new Date(end), self_.getFormat()));
      self_.hide();
    }
    first_ = !first_;
  };

  /** @inheritDoc */
  this.getDateRange = function() {
    /** @type {!Array.<Date>} */ var range = [];
    /** @type {!Date} */ var start = new Date;
    /** @type {!Date} */ var end = new Date;
    /** @type {Node} */ var element = self_.getElement();

    /** @type {number} */
    var timestamp = +element.getAttribute('data-start-date');
    if (timestamp && !isNaN(timestamp)) start = new Date(timestamp);

    timestamp = +element.getAttribute('data-end-date');
    if (timestamp && !isNaN(timestamp)) end = new Date(timestamp);

    while (start <= end) {
      range.push(start);
      start = new Date(+start + 24 * 60 * 60 * 1000);
    }
    return range;
  };

  /**
   * The reference to current class instance. Used in private methods.
   * @type {!controls.DateRangePicker}
   * @private
   */
  var self_ = this;

  /**
   * Indicates first click, selecting start date.
   * @type {boolean}
   * @private
   */
  var first_ = true;
};


/**
 * @param {Node|Element} element The related element.
 * @static
 */
controls.DateRangePicker.show = function(element) {
  if (!element.picker_) {
    element.picker_ = new controls.DateRangePicker;
  }
  element.picker_.show(element);
};

// Export for closure compiler.
controls.DateRangePicker['show'] = controls.DateRangePicker.show;

// Export for closure compiler.
controls['DateRangePicker'] = controls.DateRangePicker;
